package sdata.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import sdata.entity.Commodity;
import sdata.repository.JPARepository;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;
import java.util.*;

//@Service注解用于类上,标记当前类是一个service类,
// 加上该注解会将当前类自动注入到spring容器中,不需要再在applicationContext.xml文件定义bean了
@Service
public class CommodityService {

    @Autowired
    JPARepository jpaRepository;

    public Commodity addCom(Commodity helloItem) {
        return jpaRepository.saveAndFlush(helloItem);
    }

    public Commodity getCom(long id) {
        try {
            return jpaRepository.getById(id);
        }catch (Exception e){
            return null;
        }

    }


    public void updateCom(long id, Commodity todo) {
        try {
            jpaRepository.save(todo);
        }catch (Exception e){
            System.out.println("没有该商品");
        }

    }

    public void deleteCom(long id) {
        try{
            jpaRepository.deleteById(id);
        }catch (Exception e){
            System.out.println("没有该商品");
        }
    }

    public List<Commodity> findCom(String name) {
        //动态构造查询条件，name和complete不为null时作为条件
        Specification<Commodity> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if (name != null) {
                predicateList.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            Predicate[] predicates = predicateList.toArray(new Predicate[predicateList.size()]);
            return criteriaBuilder.and(predicates);
        };

        List<Commodity> result = jpaRepository.findAll(specification);
        return result;
    }
}
